package com.hyjx.framework.uc.depart;

import com.hyjx.framework.component.codetable.CodetableModel;
import com.hyjx.framework.component.field.ExtFieldService;
import com.hyjx.framework.orm.dao.IBaseDao;
import com.hyjx.framework.service.ConfigManager;
import com.hyjx.framework.service.UserCenterService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 部门信息服务实现类
 */
@Service
@Transactional
public class DepartServiceImpl implements DepartService {
    @Resource
    private IBaseDao dao;
    @Resource
    private ExtFieldService fieldService;

    /**
     * 添加数据对象
     *
     * @param model
     */

    public boolean add(DepartModel model) {
        dao.addObject(model.getModuleName() + ".insert", model);

        return true;
    }

    public boolean add2(DepartModel model) {
        refrershDepart();
        fieldService.update(model.getExtData());
        return true;
    }

    /**
     * 修改数据对象
     *
     * @param model
     */
    public int update(DepartModel model) {
        if ("1".equals(model.getDepart_type()))
            model.setOrg_code(model.getDepart_code());
        else {
            DepartModel model2 = (DepartModel) dao.queryObject(model.getModuleName() + ".getunitbydepartcode", model);
            if (model2 != null)
                model.setOrg_code(model2.getDepart_code());
        }
        dao.updateObject(model.getModuleName() + ".update", model);
        return 1;
    }

    public int update2(DepartModel model) {
        refrershDepart();
        fieldService.update(model.getExtData());
        return 1;
    }

    @SuppressWarnings({"unchecked", "unused"})
    private DepartModel getLeveid(DepartModel model) {
        if ("#".equals(model.getDepart_parent_code()))//如果是顶级StringUtils.isEmpty(model.getDepart_parent_code())
            model.setLevelid("001");
        else {//不是顶级
            //获取上级leveid
            String parentlevelid = this.getDepartByCode(model.getDepart_parent_code()).getLevelid();
            DepartModel dm3 = new DepartModel();
            dm3.setLevelid(parentlevelid);
            List<DepartModel> dm2 = dao.queryObjectList(model.getModuleName() + ".getSubLeveid", dm3);
            if (dm2 == null)//如果没有下级
            {
                model.setLevelid(parentlevelid + "001");
            } else//如果有下级
            {
                //取最大一个后三位
                String lastlevelid = dm2.get(dm2.size() - 1).getLevelid();
                int levelidlast3 = Integer.parseInt(lastlevelid.substring(lastlevelid.length() - 3, lastlevelid.length())) + 1;
                String levelidlast3str = String.valueOf(levelidlast3);

                while (levelidlast3str.length() < 3)//不足三位前面补0
                {
                    levelidlast3str = "0" + levelidlast3str;
                }
                model.setLevelid(parentlevelid + levelidlast3str);
            }
        }
        return model;
    }

    /**
     * 删除数据对象
     *
     * @param id
     */
    public int delete(String id) {
        return dao.deleteObject((new DepartModel()).getModuleName() + ".delete", id);
    }

    public int delete2(String id) {
        refrershDepart();
        return 1;
    }

    /**
     * 通过testid获取数据对象
     *
     * @param id
     */
    public DepartModel getDepartById(String id) {
        return (DepartModel) dao.queryObject((new DepartModel()).getModuleName() + ".getDepartById", id);
    }

    /**
     * 获取数据对象
     */
    public String getDepartList(DepartModel model) {
        return dao.getPageJsonStr(model.getModuleName() + ".getusers", model.getModuleName() + ".getusersNum", model);
    }

    /**
     * 获取数据对象
     */
    @SuppressWarnings({"unchecked"})
    public List<DepartModel> getAllDepart(DepartModel model) {
        return dao.queryObjectList(model.getModuleName() + ".getAllDepart", model);
    }

    /**
     * 重新计算levelId
     */
    private int refrershDepart() {
        DepartModel model = new DepartModel();
        List<DepartModel> list = getAllDepart(model);

        //计算levelId
        List<DepartModel> newList = calcLevelId(list, "", "");
        dao.batchUpdateObject(model.getModuleName() + ".update", newList);
        dao.updateObject(model.getModuleName() + ".updateOrgNo", null);
        updateOrgno(list);

        //计算leafnode
        refreshLeafnode(list);

        //计算depart_code_full
        refreshDepart_code_full(list);
        return 1;
    }

    private void updateOrgno(List<DepartModel> list) {
        for (DepartModel dm : list) {
            if (dm.getDepart_type().equals("0")) {
                List<DepartModel> departlist = this.getDepartByCodes(dm.getDepart_code_full().substring(0, dm.getDepart_code_full().length() - 1).replaceAll("\\.", "\\,"));
                for (int i = 0; i < departlist.size(); i++) {
                    if (departlist.get(i).getDepart_type().equals("1")) {
                        dm.setOrg_code(departlist.get(i).getOrg_code());
                        continue;
                    }
                }
            }
        }
        dao.batchUpdateObject((new DepartModel()).getModuleName() + ".update", list);
    }

    private String findOrgCode(DepartModel dm, List<DepartModel> list) {
        for (DepartModel d : list) {
            if (d.getDepart_code().equals(dm.getDepart_parent_code()) && d.getDepart_type().equals("1")) {
                return d.getDepart_code();
            } else if (d.getDepart_id().equals(dm.getDepart_parent_code()) && d.getDepart_type().equals("0")) {
                return findOrgCode(d, list);
            }
        }
        return null;
    }

    private void refreshDepart_code_full(List<DepartModel> list) {
        for (DepartModel temp : list) {
            for (DepartModel temp1 : list) {
                if (temp1.getDepart_code().equals(temp.getDepart_code())) {
                    String full_code = temp.getDepart_code() + ".";
                    DepartModel temp2 = new DepartModel();
                    temp2 = temp1;
                    while (temp2 != null) {
                        temp2 = contactDepart_code(temp2.getDepart_parent_code(), list);
                        if (temp2 != null)
                            full_code = temp2.getDepart_code() + "." + full_code;
                    }
                    temp.setDepart_code_full(full_code);
                }
            }
        }
        dao.batchUpdateObject((new DepartModel()).getModuleName() + ".updatefullcode", list);
    }

    private DepartModel contactDepart_code(String pcode, List<DepartModel> list) {
        for (DepartModel temp : list) {
            if (temp.getDepart_id().equals(pcode)) {
                return temp;
            }
        }
        return null;
    }

    private void refreshLeafnode(List<DepartModel> list) {
        String leafnode = "";
        String notleafnode = "";
        for (DepartModel dm : list) {
            boolean isleafnode = true;
            for (DepartModel dm2 : list) {
                if (dm.getDepart_code().equals(dm2.getDepart_parent_code())) {
                    isleafnode = false;
                }
            }
            if (isleafnode)
                leafnode += dm.getDepart_code() + ",";
            else
                notleafnode += dm.getDepart_code() + ",";
        }
        if (leafnode.endsWith(","))
            leafnode = leafnode.substring(0, leafnode.length() - 1);
        if (notleafnode.endsWith(","))
            notleafnode = notleafnode.substring(0, notleafnode.length() - 1);
        DepartModel dm = new DepartModel();
        dm.setDepart_code(notleafnode);
        dm.setIs_leaf_node("0");
        dao.updateObject(dm.getModuleName() + ".updateleafnode", dm);
        dm.setDepart_code(leafnode);
        dm.setIs_leaf_node("1");
        dao.updateObject(dm.getModuleName() + ".updateleafnode", dm);

    }

    /**
     * 递归刷新LevelId
     */
    private List<DepartModel> calcLevelId(List<DepartModel> list, String parentId, String levelId) {
        List<DepartModel> children = new ArrayList<DepartModel>();
        List<DepartModel> returnList = new ArrayList<DepartModel>();
        //取到某一层数据
        for (DepartModel departModel : list) {
            String modelPId = "#".equals(departModel.getDepart_parent_code()) ? "" : departModel.getDepart_parent_code();
            if (parentId.equals(modelPId)) {
                children.add(departModel);
            }
        }
        int childrenCount = children.size();
        if (childrenCount > 0) {
            //排序
            DepartModelSortAsc comparator = new DepartModelSortAsc();
            Collections.sort(children, comparator);
            //取到某一层数据
            Integer count = 0;
            for (DepartModel model : children) {
                count++;
                model.setLevelid(levelId + String.format("%03d", count));
                List<DepartModel> grandson = calcLevelId(list, model.getDepart_code(), model.getLevelid());
                if (grandson.size() > 0) {
                    returnList.addAll(grandson);
                    model.setIs_leaf_node("0");
                } else {
                    model.setIs_leaf_node("1");
                }
            }
        }
        returnList.addAll(children);
        return returnList;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public String validate(DepartModel model) {
        List ls = null;
        String c = model.getDepart_code();
        String n = model.getDepart_name();
        model.setDepart_name("");
        if (model.getDepart_code() != null) {
            ls = dao.queryObjectList(model.getModuleName() + ".validate", model);
            if (ls != null && ls.size() > 0)
                return "部门编码重复";
        }
        if (model.getDepart_name() != null) {
            model.setDepart_code("");
            String namenunique = ConfigManager.getConfig("sys.depart.nameunique");
            if (!"2".equals(namenunique)) {
                model.setOrg_code(UserCenterService.getCurrentUserInfo().getOrg_code());
            }
            model.setDepart_name(n);
            ls = dao.queryObjectList(model.getModuleName() + ".validate", model);
            if (ls != null && ls.size() > 0)
                return "部门名称重复";
        }
        return null;

    }

    @Override
    public String getMaxCodeByParentId(DepartModel departModel) {
        String parentId = departModel.getDepart_parent_code();
        String maxCode = null;
        maxCode = (String) (dao.queryObject(departModel.getModuleName() + ".getMaxCodeByParentId", departModel));

        DepartModel parentModel = getDepartById(parentId);
        int departcodelen = StringUtils.isEmpty(ConfigManager.getConfig("departcodelen")) ? 3 : Integer.parseInt(ConfigManager.getConfig("departcodelen"));

        if (StringUtils.isEmpty(maxCode)) {
            maxCode = "1";
            int maxCodelen = maxCode.length();
            if (maxCodelen < departcodelen) {
                for (int i = 0; i < departcodelen - maxCodelen; i++) {
                    maxCode = "0" + maxCode;
                }
            }
            maxCode = parentModel.getDepart_code() + maxCode;
        } else {
            int last3 = Integer.parseInt(maxCode.substring(maxCode.length() - 3, maxCode.length()));
            String last3str = String.valueOf(last3 + 1);
            if (last3str.length() == 1)
                last3str = "00" + last3str;
            else if (last3str.length() == 2)
                last3str = "0" + last3str;
            maxCode = maxCode.substring(0, maxCode.length() - 3) + last3str;
        }

        return maxCode;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<DepartModel> getDepartModelList(DepartModel model) {
        return dao.queryObjectList(model.getModuleName() + ".getDepartModelList", model);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<DepartModel> getSubDepart(DepartModel model) {
        if (StringUtils.isEmpty(model.getDepart_code())) return null;
        return dao.queryObjectList(model.getModuleName() + ".getSubDepart", model);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<DepartModel> getAllDepart2(DepartModel departModel) {
        return dao.queryObjectList(departModel.getModuleName() + ".getAllDepart2", departModel);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<DepartModel> getDepartByCodes(String depart_codes) {
        depart_codes = "'" + depart_codes.replaceAll(",", "','") + "'";
        return dao.queryObjectList((new DepartModel()).getModuleName() + ".getDepartByCodes", depart_codes);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<DepartModel> getSomeDepart(String bmids) {
        if (bmids == null) return null;
        bmids = "'" + bmids.replaceAll(",", "','") + "'";
        return dao.queryObjectList((new DepartModel()).getModuleName() + ".getSomeDepart", bmids);
    }

    @Override
    public DepartModel getDepartByCode(String depart_code) {
        return (DepartModel) dao.queryObject((new DepartModel()).getModuleName() + ".getDepartByCode", depart_code);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<CodetableModel> queryconfigtree(String sql) {
        return (List<CodetableModel>) dao.queryObjectList((new DepartModel()).getModuleName() + ".queryconfigtree", sql);
    }

    @Override
    public String getDepart_city(DepartModel model) {
        if (model.getDepart_code_full().endsWith("."))
            model.setDepart_code_full(model.getDepart_code_full().substring(0, model.getDepart_code_full().length() - 1));
        model.setDepart_code_full("'" + model.getDepart_code_full().replaceAll("\\.", "','") + "'");
        return (String) dao.queryObject(model.getModuleName() + ".getDepart_city", model);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<DepartModel> getRootCode(DepartModel model) {
        return (List<DepartModel>) dao.queryObjectList(model.getModuleName() + ".getRootCode", model);
    }

    @Override
    public String getFullDepartCN(String depart_code) {
        DepartModel dm = getDepartByCode(depart_code);
        try {
            dm.setDepart_code_full(dm.getDepart_code_full().substring(0, dm.getDepart_code_full().length() - 1).replaceAll("\\.", "\\,"));
        } catch (Exception ex) {
        }
        List<DepartModel> listdm = getSomeDepart(dm.getDepart_code_full());
        String departCN = "";
        if (listdm != null) {
            for (DepartModel dm2 : listdm) {
                departCN += dm2.getDepart_name() + "/";
            }
            if (departCN.endsWith("/")) departCN = departCN.substring(0, departCN.length() - 1);
        }
        return departCN;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<DepartModel> getUnit(DepartModel model) {
        return (List<DepartModel>) dao.queryObjectList(model.getModuleName() + ".getunit", model);
    }

    @Override
    public String getMaxOrderNoByParentId(DepartModel model) {
        return (String) dao.queryObject(model.getModuleName() + ".getMaxOrderNoByParentId", model);
    }

    @Override
    public DepartModel getOrgCodeByDepartCode(DepartModel model) {
        return (DepartModel) dao.queryObject(model.getModuleName() + ".getunitbydepartcode", model);
    }

    @Override
    public List queryObjectList(String sql) {
        return (List) dao.queryObjectList("codetable.querySqlTableList", sql);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<DepartModel> getAllSubDepart(DepartModel model) {
        return (List) dao.queryObjectList(model.getModuleName() + ".getAllSubDepart", model);
    }

    public static void main(String[] args) {
        System.out.println(String.format("%03d", 112));
    }

    @Override
    public int logic_delete(String id) {
        return dao.updateObject((new DepartModel()).getModuleName() + ".logic_delete", id);
    }
}